package com.szbmyoubao.app.http

import android.app.Application
import android.app.Dialog
import com.szbmyoubao.app.http.interceptor.CommonHeaderInterceptor
import com.ellecity06.common.base.BaseViewModel
import com.ellecity06.common.base.view.LoadUiIntent
import com.ellecity06.common.http.BaseRetrofitClient
import com.ellecity06.common.http.entity.ApiResponse
import com.ellecity06.common.http.launchFlow
import com.ellecity06.common.utils.ToastUtils
import com.ellecity06.common.utils.appContext
import com.szbmyoubao.app.DebugManager
import kotlinx.coroutines.CoroutineScope
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import java.util.concurrent.TimeUnit

object RetrofitClient : BaseRetrofitClient() {

    val service by lazy { getService(ApiService::class.java, ServerConfig.baseHost) }

    /**
     * 用户上传操作 超时时间比较长
     */
    val service2 by lazy { getService2(ApiService::class.java, ServerConfig.baseHost) }

    val downloadService: ApiService by lazy {
        Retrofit.Builder()
            .client(
                OkHttpClient.Builder()
                    .readTimeout(120, TimeUnit.SECONDS)
                    .connectTimeout(120, TimeUnit.SECONDS)
                    .build()
            )
            .baseUrl(ServerConfig.baseHost)
            .build()
            .create(ApiService::class.java)
    }

    override fun handleBuilder(builder: OkHttpClient.Builder) {
        builder.addInterceptor(CommonHeaderInterceptor())
        DebugManager.addLogInterceptor(appContext as Application, builder)
    }
}

fun <T> BaseViewModel.request(
    api: suspend ApiService.() -> ApiResponse<T>,
    success: suspend (T?) -> Unit = {},
    showLoading: Boolean = false,
    loadText: String = "加载中...",
    tokenExpired: ((String) -> Unit)? = {
        sendLoadUiIntent(LoadUiIntent.AuthorizationExpired(it))
    },
    error: suspend (Throwable) -> Unit = { t ->
        //默认异常处理，子类可以进行覆写
        sendLoadUiIntent(LoadUiIntent.Error(t.message ?: "系统异常"))
    }
) {
    launchFlow(
        body = { api.invoke(RetrofitClient.service) },
        success = success,
        showLoading = showLoading,
        loadText = loadText,
        tokenExpired = tokenExpired,
        error = error,
    )

}

fun <T> BaseViewModel.requestByUpload(
    api: suspend ApiService.() -> ApiResponse<T>,
    success: suspend (T?) -> Unit = {},
    showLoading: Boolean = false,
    loadText: String = "生成中...",
    tokenExpired: ((String) -> Unit)? = {
        sendLoadUiIntent(LoadUiIntent.AuthorizationExpired(it))
    },
    error: suspend (Throwable) -> Unit = { t ->
        //默认异常处理，子类可以进行覆写
        sendLoadUiIntent(LoadUiIntent.Error(t.message ?: "系统异常"))
    }
) {
    launchFlow(
        body = { api.invoke(RetrofitClient.service2) },
        success = success,
        showLoading = showLoading,
        loadText = loadText,
        tokenExpired = tokenExpired,
        error = error,
    )

}

fun <T> CoroutineScope.request(
    api: suspend ApiService.() -> ApiResponse<T>,
    success: suspend (T?) -> Unit = {},
    loadText: String = "加载中...",
    tokenExpired: ((String) -> Unit)? = {

    },
    loading: Dialog? = null,
    error: suspend (Throwable) -> Unit = { t ->
        //默认异常处理，子类可以进行覆写
        ToastUtils.show(t.message ?: "系统异常")
    }
) {
    launchFlow(
        body = { api.invoke(RetrofitClient.service) },
        success = success,
        loadText = loadText,
        tokenExpired = tokenExpired,
        loading = loading,
        error = error,
    )

}
